import socket, threading, time, sys
import subprocess as sp
import os
from settings import *
import json
remove = 'rm' in sys.argv

def dbtest():
    if os.path.exists('caster.db') and remove:
        os.remove('caster.db')
    import database as db
    db.create()
    s=db.Session()
    l = s.query(db.Location).first()
    print l.draw()


def apptest():
    sock=socket.socket()
    sock.connect(('localhost',LISTEN_PORT))
    sock.settimeout(None)
    run = True
    def recv():
        while True:
            if not run:
                break
            try:
                data = sock.recv(20000)
            except:
                continue
            if not data:
                break
            print "<<<"+data

    t=threading.Thread(target=recv)
    t.start()
    def send(msg):
        print ">>>"+msg
        sock.sendall(msg)
        time.sleep(0)
    def s(cmd):
        if type(cmd) is not list:
            cmd = [cmd]
        for line in cmd:
            send(line+'\r\n')
    for line in [
{"what":"login", "login":"demoth", "passw":"asdf"},
{"what":"join", "crid":2},
{"what":"inventory"},
#{"what":"request", "type":"move", "info":"W"},
#{"what":"request", "type":"move", "info":"W"},
#{"what":"request", "type":"move", "info":"W"},
{"what":"request", "type":"pick", "target":4},
{"what":"request", "type":"drop", "target":4},
{"what":"request", "type":"pick", "target":4},
{"what":"request", "type":"commit"},
{"what":"inventory"},
                 #{"what":"request", "type":"pick", "target":"4"}
                 #{"what":"request", "type":"drop", "target":"4"}
                 #{"what":"request", "type":"move", "info":"W"}
                 #{"what":"inventory"}
                 ]:
        send(json.dumps(line)+'\r\n')
        time.sleep(0.5)
    run = False

if 'db' in sys.argv or 'rm' in sys.argv:
    dbtest()
if 'app' in sys.argv:
    apptest()

